package com.teach.ser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * <pre>
 * - 序列化 serialization 
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-4-27 10:00:28
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
public class ObjectToStream {

	public static void main(String[] args)throws Exception {
		Student obj = new Student("张三", 18, 100f);
		Student.setSchool("湖南大学");
		System.out.println(obj);
		File file = new File("d:/upload/object");
		try(
			OutputStream out = new FileOutputStream(file);
			ObjectOutputStream oout = new ObjectOutputStream(out);
				){
			oout.writeObject(obj);//可能：java.io.NotSerializableException
//			oout.flush();
		}
		
		//使用序列化技术完成对象克隆
		
		try(
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				ObjectOutputStream oout = new ObjectOutputStream(out);
				
					){
				oout.writeObject(obj);//可能：java.io.NotSerializableException
				
				try(
					ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
					ObjectInputStream oin = new ObjectInputStream(in);
				){
					Object newObj = oin.readObject();
					System.out.println(newObj);
				}
				
//				oout.flush();
			}
	}
}
